package com.itserver.utils;

import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Slf4j
@EnableScheduling
@Configuration
public class TimerTask {

    @Autowired
    private RedisCache redisCache;
    /*
     * 定时任务
     * */
    @Scheduled(fixedRate = 1000 * 60)
    public void task() {
        log.info("定时任务开始执行...");
        // 删除过期的token
        List<String> tokenList = redisCache.getInvalidTokenList();
        for (String token : tokenList) {
            Claims claims = JwtUtils.parseJWT(token);
            if (claims == null) {
                redisCache.deleteInvalidToken(token);
            }
        }
        // 登录过期用户
        Map<String, String> loginUserList = redisCache.getLoginUsers();
        List<String> loginUsers = new ArrayList<>();
        loginUserList.forEach((key, value) -> {
            loginUsers.add(key);
        });
        log.info("无效token列表...{}",  tokenList.size());
        log.info("在线登录用户列表...{}",  loginUsers);
    }
}
